/*
Copyright © 2024 NAME HERE <EMAIL ADDRESS>
*/
package cmd

import (
	"bytes"
	"fmt"
	"log"
	"net"
	"os"

	"gitee.com/spark-community-works-collections/shenmo-water-pipe/utils"

	"github.com/spf13/cobra"
)

func HandleConnChan(client chan net.Conn, clientAccess chan int, shell chan net.Conn, shellAccess chan int, l net.Listener) {
	for {
		conn, _ := l.Accept()
		// 访问验证
		if !utils.CheckPolicy(conn, ACCESS_POLICY) {
			log.Printf("发现请求连接：%v (未通过)", conn.RemoteAddr().String())
			continue
		}
		log.Printf("发现请求连接：%v (已认证)", conn.RemoteAddr().String())

		// 策略验证
		var buffer = make([]byte, len(ACCESS_POLICY))
		conn.Read(buffer)

		if bytes.Equal(buffer, []byte(ACCESS_RESET_POLICY)) {
			conn.Write([]byte("shenmo-water-pip: 服务器正在重启\n"))
			os.Exit(-1)
		}

		if bytes.Equal(buffer, []byte(ACCESS_TRANSFER_POLICY)) {
			clientAccess <- 1
			client <- conn
		}
		if bytes.Equal(buffer, []byte(ACCESS_SHELL_POLICY)) {
			shellAccess <- 1
			shell <- conn
		}
	}
}

// serverCmd represents the server command
var serverCmd = &cobra.Command{
	Use:   "server",
	Short: "小水管服务器",
	Long:  ``,
	Run: func(cmd *cobra.Command, args []string) {
		from, _ := cmd.Flags().GetInt("from")
		to, _ := cmd.Flags().GetInt("to")

		froml, _ := net.Listen("tcp", fmt.Sprintf("0.0.0.0:%v", from))
		tol, _ := net.Listen("tcp", fmt.Sprintf("0.0.0.0:%v", to))
		fmt.Printf("Shenmo Pipe Listening: %v -> %v\n", from, to)

		fromAccess := make(chan int)
		fromChan := make(chan net.Conn)
		toAccess := make(chan int)
		toChan := make(chan net.Conn)

		sharedAccess := make(chan int)
		sharedChan := make(chan net.Conn)

		attachAccess := make(chan int)
		attachChan := make(chan net.Conn)

		go HandleConnChan(fromChan, fromAccess, sharedChan, sharedAccess, froml)
		go HandleConnChan(toChan, toAccess, attachChan, attachAccess, tol)

		for {
			select {
			case <-fromAccess:
				log.Print("发现先手 Push 动作，等待 Pull")
				fromConn := <-fromChan
				<-toAccess
				toConn := <-toChan
				go utils.TransferData(fromConn, toConn)
				log.Printf("Transfer: from %v to %v", fromConn.RemoteAddr().String(), toConn.RemoteAddr().String())
			case <-toAccess:
				log.Println("发现先手 Pull 动作，等待 Push")
				toConn := <-toChan
				<-fromAccess
				fromConn := <-fromChan
				go utils.TransferData(fromConn, toConn)
				log.Printf("Transfer: from %v to %v", fromConn.RemoteAddr().String(), toConn.RemoteAddr().String())
			case <-sharedAccess:
				log.Println("发现先手 Shared 动作，等待 Attach")
				sharedConn := <-sharedChan
				<-attachAccess
				attachConn := <-attachChan
				go utils.SwapData(sharedConn, attachConn)
				log.Printf("Shell: shared %v to %v", sharedConn.RemoteAddr().String(), attachConn.RemoteAddr().String())
			case <-attachAccess:
				log.Println("发现先手 Attach 动作，等待 Shared")
				attachConn := <-attachChan
				<-sharedAccess
				sharedConn := <-sharedChan
				go utils.SwapData(sharedConn, attachConn)
				log.Printf("Shell: shared %v to %v", sharedConn.RemoteAddr().String(), attachConn.RemoteAddr().String())
			}
		}
	},
}

func init() {
	rootCmd.AddCommand(serverCmd)

	// Here you will define your flags and configuration settings.

	// Cobra supports Persistent Flags which will work for this command
	// and all subcommands, e.g.:
	// serverCmd.PersistentFlags().String("foo", "", "A help for foo")

	// Cobra supports local flags which will only run when this command
	// is called directly, e.g.:
	// serverCmd.Flags().BoolP("toggle", "t", false, "Help message for toggle")
	serverCmd.Flags().IntP("from", "f", 6700, "绑定来源端口")
	serverCmd.Flags().IntP("to", "t", 6800, "绑定目标端口")
}
